from django.shortcuts import render

# Create your views here.

from workflow.models import (
    Workflow,
    WorkflowPermission,
    WorkflowApprovalNode,
    Task,
    AuditRecord
)

from workflow.ser import (
    WorkflowSerializer,
    WorkflowPermissionSerializer,
    WorkflowApprovalNodeSerializer,
    TaskSerializer,
    AuditRecordSerializer
)

from admins.models import (
    RoleModel,
    AdminUserModel,
    Department,
    Position,
)

from admins.ser import (
    RoleSerializer,
    AdminUserSerializer,
    DepartmentSerializer,
    PositionSerializer
)

from rest_framework.viewsets import ViewSet
from rest_framework.generics import (
    ListAPIView,
    CreateAPIView,
    DestroyAPIView,
    RetrieveAPIView,
    UpdateAPIView,
    RetrieveUpdateAPIView,
    ListCreateAPIView,
    RetrieveUpdateDestroyAPIView,
)

import time, json
from tools.myjwt import mjwt
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from workflow.myagent import audit_workflow

# 部门视图
class DepartmentListCreateView(APIView):
    def post(self, request, format=None):
        serializer = DepartmentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

# 职位视图
class PositionListCreateView(APIView):
    def post(self, request, format=None):
        serializer = PositionSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

# 用户视图
class StaffView(APIView):
    permission_classes = [IsAuthenticated]

    def get_object(self, pk):
        try:
            return AdminUserModel.objects.get(pk=pk)
        except AdminUserModel.DoesNotExist:
            return None

    def get(self, request, pk=None):
        if pk:
            staff = self.get_object(pk)
            if staff:
                serializer = AdminUserSerializer(staff)
                return Response(serializer.data)
            return Response({"error": "Staff not found"}, status=status.HTTP_404_NOT_FOUND)
        else:
            # 如果没有提供 pk，则返回所有员工列表
            staff_list = AdminUserModel.objects.all()
            serializer = AdminUserSerializer(staff_list, many=True)
            return Response(serializer.data)

    def post(self, request):
        # 从请求中获取数据
        name = request.data.get('name')
        role_id = request.data.get('role_id')
        dept_id = request.data.get('dept_id')
        position_id = request.data.get('position_id')
        phone = request.data.get('phone')
        password = request.data.get('password')

        # 验证角色、部门和职位是否存在
        try:
            role = RoleModel.objects.get(id=role_id)
            department = Department.objects.get(id=dept_id)
            position = Position.objects.get(id=position_id)
        except (RoleModel.DoesNotExist, Department.DoesNotExist, Position.DoesNotExist):
            return Response({"error": "Role, Department or Position not found"}, status=status.HTTP_404_NOT_FOUND)

        # 创建员工数据
        user_data = {
            'name': name,
            'role': role,
            'dept_id': dept_id,
            'position_id': position_id,
            'phone': phone,
            'password': password  # 注意：实际应用中应该对密码进行加密处理
        }

        # 使用序列化器验证数据和创建用户
        serializer = AdminUserSerializer(data=user_data)
        if serializer.is_valid(raise_exception=True):
            user = serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def put(self, request, pk):
        staff = self.get_object(pk)
        if not staff:
            return Response({"error": "Staff not found"}, status=status.HTTP_404_NOT_FOUND)
        data = request.data
        data['role'] = RoleModel.objects.get(id=data.get('role_id'))
        data['dept_id'] = Department.objects.get(id=data.get('dept_id'))
        data['position_id'] = Position.objects.get(id=data.get('position_id'))
        serializer = AdminUserSerializer(staff, data=data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def patch(self, request, pk):
        staff = self.get_object(pk)
        if not staff:
            return Response({"error": "Staff not found"}, status=status.HTTP_404_NOT_FOUND)
        serializer = AdminUserSerializer(staff, data=request.data, partial=True)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        staff = self.get_object(pk)
        if not staff:
            return Response({"error": "Staff not found"}, status=status.HTTP_404_NOT_FOUND)
        staff.delete()
        return Response({"message": "Staff deleted successfully"}, status=status.HTTP_204_NO_CONTENT)

# 增加工作流
class AddWorkflowListView(APIView):
    def post(self, request, format=None):
        json_string = json.dumps(request.data, ensure_ascii=False)
        data_dict = json.loads(json_string)
        serializer = WorkflowSerializer(data=data_dict)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

# 增加工作流角色
class AddWorkflowRoleView(APIView):
    def post(self, request):
        workflow_id = request.data.get('workflow_id')
        role_id = request.data.get('role_id')
        # 检查工作流和角色是否存在
        try:
            workflow = Workflow.objects.get(id=workflow_id)
            role = RoleModel.objects.get(id=role_id)
        except (Workflow.DoesNotExist, RoleModel.DoesNotExist):
            return Response({'error': '找不到工作流ID或角色ID'}, status=status.HTTP_404_NOT_FOUND)
        # 创建工作流权限对象
        workflow_permission = WorkflowPermission.objects.create(role_id=role, workflow_id=workflow)
        # 使用序列化器序列化创建的对象
        serializer = WorkflowPermissionSerializer(workflow_permission)
        return Response({"data":serializer.data, "status":status.HTTP_201_CREATED})

# 获取角色的工作流列表
class ListWorkflowView(ListAPIView):
    serializer_class = WorkflowSerializer

    def get_queryset(self):
        # 获取 Authorization 头部中的 token
        token = self.request.headers.get("Authorization")
        if not token:
            return Workflow.objects.none()  # 如果没有 token，返回空查询集
        try:
            # 解码 token 获取角色ID
            data = mjwt.jwt_decode(token)
            role_id = data.get("data").get("role")
        except Exception as e:
            # 如果 token 解码失败，返回空查询集
            return Workflow.objects.none()
        # 根据角色ID查询工作流权限
        workflow_ids = WorkflowPermission.objects.filter(role_id=role_id).values_list("workflow_id", flat=True)
        # 查询用户有权限访问的工作流列表
        workflow_list = Workflow.objects.filter(id__in=workflow_ids)
        return workflow_list

# 添加工作流审批
class WorkflowApprovalNodeCreateView(CreateAPIView):
    queryset = WorkflowApprovalNode.objects.all()
    serializer_class = WorkflowApprovalNodeSerializer

# 查看审批流程
class WorkflowApprovalNodeListView(APIView):
    # 传递两个参数 Authorization 和 workflow_id 到视图
    def get(self, request):
        token = request.headers.get("Authorization")
        print(token)
        data = mjwt.jwt_decode(token)
        print(data)
        user_id = data.get("data").get("id")
        print(user_id)
        department_id = AdminUserModel.objects.get(id=user_id).dept_id
        workflow_id = request.query_params.get('workflow_id')
        print("workflow_id:", workflow_id)
        print("department_id:", department_id)
        position = WorkflowApprovalNode.objects.filter(workflow_id=workflow_id)
        print("position:", position)
        position_list = position.values_list("position_id", flat=True)
        print("position_list:", position_list)
        user = AdminUserModel.objects.filter(position_id__in=position_list, dept_id_id=department_id).order_by("position_id")
        print("user:", user)
        user_list = user.values_list("name", flat=True)
        print("user_list:", user_list)
        print("---------------------------")
        return Response({"user_list": user_list})

# 调用Agent创建任务表
class TaskCreateView(APIView):
    def post(self, request):
        # 需要接收字段: name, params, workflow_id, userid, task_status
        token = request.headers.get("Authorization")
        userid = mjwt.jwt_decode(token).get("data").get("id")
        print(userid)
        message = request.data.get("message")
        print(message)
        message["name"] = message.get("params")[0].get("value") + "的出差申请"
        message["userid"] = userid
        message["task_status"] = 0
        the_message = json.dumps(message)
        data = audit_workflow(json.dumps({"title": "创建新任务", "message": the_message}))
        print("返回的任务id:", data["output"])
        response = data["output"]
        # 如果成功存入
        try:
            int(response)
            # 获取第一审批人
            response = audit_workflow(json.dumps({"title": "获取下一审批人", "message": data["output"]}))
            return Response({"code": 200, "response": response})
        except Exception:
            return Response({"code": 400, "response": response})

# 调用Agent获取下一审批人
class NextReviewerView(APIView):
    def post(self, request):
        # 需要接受字段：task_id, audit_user, audit_status, note
        message = request.data.get("message")

        # 填写审批表单
        data = audit_workflow({"title": "填写审批记录", "message": message})

        # 本审批人审批通过
        if message.get("audit_status") == 0:
            flag = audit_workflow({"title": "获取下一审批人", "message": message.get("task_id")})
        else:
            return Response({"response": "审批不通过"})
        return Response({"response": data})